package com.f_mai.im;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;

public class ChatActivity extends Activity implements Callback, OnClickListener {
	private String targetUser;
	
	private Handler handler;
	private ListView chatList;
	private MsgListAdapter adapter;
	
	//底部发送消息模块
	private EditText mInputEt;
	private Button mSendMsgBtn;
	private ImageButton mAddFileIb;
	private TableLayout more_menu_tl;
	private long groupId;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		JMessageClient.registerEventReceiver(this);
		setContentView(R.layout.activity_chat);
		targetUser = getIntent().getStringExtra("targetUser");
		groupId = getIntent().getLongExtra("groupId", 0);
		initTitleBar();
		chatList = (ListView) findViewById(R.id.chat_list);
		handler = new Handler(this);
		if (groupId == 0) {
			adapter = new MsgListAdapter(this, targetUser);
		} else {
			adapter = new MsgListAdapter(this, groupId);
		}
		chatList.setAdapter(adapter);
		initBtmSendMsg();
	}

	private void initBtmSendMsg() {
		mSendMsgBtn = (Button) findViewById(R.id.send_msg_btn);
		mSendMsgBtn.setOnClickListener(this);
		mAddFileIb = (ImageButton) findViewById(R.id.add_file_btn);
		mAddFileIb.setOnClickListener(this);
		more_menu_tl = (TableLayout) findViewById(R.id.more_menu_tl);
		mInputEt = (EditText) findViewById(R.id.chat_input_et);
//		mInputEt.addTextChangedListener(watcher);
//		mInputEt.setOnFocusChangeListener(listener);
        mInputEt.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        mInputEt.setSingleLine(false);
       /* mInputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_DONE){
                    dismissMoreMenu();
                    Log.i("ChatView", "dismissMoreMenu()----------");
                }
                return false;
            }
        });*/
        mInputEt.setMaxLines(4);
	}

	private void initTitleBar() {
		findViewById(R.id.return_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		if (groupId == 0) {
			((TextView)findViewById(R.id.title)).setText(targetUser);
		} else {
			((TextView)findViewById(R.id.title)).setText("群组"+groupId);
		}
	}

	/**
	 * 接收消息类事件
	 * 
	 * @param event
	 *            消息事件
	 */
	public void onEvent(MessageEvent event) {
		Message msg = event.getMessage();
		android.os.Message message = handler.obtainMessage();
		message.obj = msg;
		handler.sendMessage(message);
	}

	@Override
	public boolean handleMessage(android.os.Message message) {
		Message msg = (Message) message.obj;
		adapter.refresh();
		Toast.makeText(this, "type:" + msg.getContentType() + ";content:" + msg.getContent().toJson(), 1).show();
		Log.i("baadoo", "type:" + msg.getContentType() + ";content:" + msg.getContent().toJson());
		return false;
	}
	/**
	 * 释放资源
	 */
	@Override
	protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
		super.onDestroy();
	}
	private TextWatcher watcher = new TextWatcher(){
		private CharSequence temp = "";
		@Override
		public void afterTextChanged(Editable arg0) {
			if(temp.length() > 0){
				mAddFileIb.setVisibility(View.GONE);
				mSendMsgBtn.setVisibility(View.VISIBLE);
			}else{
				mAddFileIb.setVisibility(View.VISIBLE);
				mSendMsgBtn.setVisibility(View.GONE);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int count,
				int after) {
			temp = s;
		}

	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_msg_btn:
			String sendTxt = mInputEt.getText().toString();
			if (TextUtils.isEmpty(sendTxt)) {
				Toast.makeText(this, "发送内容不可为空", Toast.LENGTH_SHORT).show();
				return;
			}
			Conversation conv = null;
			if (groupId == 0) {
				conv = JMessageClient.getSingleConversation(targetUser);
			} else {
				conv = JMessageClient.getGroupConversation(groupId);
			}
			TextContent text = new TextContent(sendTxt);
			Message msg;
			if (conv == null) {
				if (groupId == 0) {//点对点
					msg = JMessageClient.createSingleTextMessage(targetUser, sendTxt);
				}else {
					msg = JMessageClient.createGroupTextMessage(groupId, sendTxt);
				}
			} else {
				msg = conv.createSendMessage(text);
			}
			adapter.addMsgToList(msg);
	    	JMessageClient.sendMessage(msg);
	    	mInputEt.setText("");
			break;
		case R.id.add_file_btn:
			more_menu_tl.setVisibility(View.VISIBLE);
			break;
		}
	}
}
